package de.tsystems.dict.api.impl;

import com.google.common.base.Preconditions;
import de.tsystems.dict.api.LanguageService;
import de.tsystems.dict.api.WordService;
import de.tsystems.dict.model.Language;
import de.tsystems.dict.model.Word;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.Transactional;

import javax.inject.Inject;
import javax.inject.Named;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;

@Named("languageService")
class LanguageServiceImpl implements LanguageService {

    @Named("languageDao")
    @Inject
    private LanguageDao languageDao;

    @Inject
    @Named("wordService")
    private WordService wordService;

    public void setLanguageDao(LanguageDao dao) {
        languageDao = dao;
    }

    public LanguageDao getLanguageDao() {
        return languageDao;
    }

    @Override
    @Transactional
    public Language create(String name) {
            Preconditions.checkArgument(StringUtils.isNotBlank(name));
            return languageDao.create(name);
    }

    public WordService getWordService() {
        return wordService;
    }

    public void setWordService(WordService wordService) {
        this.wordService = wordService;
    }

    @Override
    @Transactional
    public Language save(Language language) {
        Preconditions.checkNotNull(language);
        Preconditions.checkArgument(
            StringUtils.isNotBlank(language.getName()),
            "Language name cannot be empty"
        );
        return languageDao.save(language);
    }

    @Override
    @Transactional(readOnly = true)
    public Language getById(Serializable id) {
        Preconditions.checkNotNull(id);
        return languageDao.getById(id);
    }

    @Override
    @Transactional(readOnly = true)
    public List<Language> listAll() {
        return languageDao.listAll();
    }

    @Override
    @Transactional(readOnly = true)
    public Language findLanguage(String languageCode) {
        return languageDao.findByName(languageCode); //FIXME: change to appropriate name
    }

   @Override
   @Transactional
   public void remove(@NotNull Language language) {
       for (Word word : languageDao.getWords(language)) {
           wordService.remove(word);
       }
      languageDao.remove(language);
   }
}